package com.kxf.androidtestdemo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.view.View;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.kxf.androidtestdemo.R;
import com.kxf.androidtestdemo.bean.ActivityResultCallbackBean;
import com.kxf.androidtestdemo.fragments.ActivityResultCallbackFragment;
import com.kxf.androidtestdemo.interfaces.IRemoteActivityCallback;
import com.kxf.androidtestdemo.view.LogTxtView;
import com.kxf.utils.Util;

import java.lang.ref.WeakReference;

public class RegisterForActivityResultActivity extends BaseActivity {

    public static final int MSG_FROM_CLIENT = 0x10001;
    public static final int MSG_TO_CLIENT = 0x10002;
    public static final int MSG_CONN_SUCCESS = 0x10003;
    public static final int MSG_DIS_CONN = 0x10004;
    public static final String MSG_KEY = "messenger";

    private static final String TAG_FRAGMENT = "activityResultCallbackFragment";
    private ActivityResultCallbackFragment activityResultCallbackFragment;
    public static WeakReference<IRemoteActivityCallback> remoteActivityCallback = null;
    private LogTxtView logTxtView;

    ActivityResultContract activityResultContract = new ActivityResultContract<Intent, ActivityResultCallbackBean>() {
        @NonNull
        @Override
        public Intent createIntent(@NonNull Context context, Intent input) {
            return input;
        }

        @Override
        public ActivityResultCallbackBean parseResult(int resultCode, @Nullable Intent intent) {
            ActivityResultCallbackBean bean = new ActivityResultCallbackBean();
            if (intent != null){
                bean.setCode(intent.getIntExtra("code", -1));
                bean.setResultStr(intent.getStringExtra("resultStr"));
            }
            return bean;
        }
    };
    ActivityResultCallback callback = new ActivityResultCallback<ActivityResultCallbackBean>() {
        @Override
        public void onActivityResult(ActivityResultCallbackBean result) {
            logTxtView.showTxt("onActivityResult  result=" + result);
        }
    };
    //registerForActivityResult一定要在onCreate或者onCreate之前调用，要不然报错
    //Caused by: java.lang.IllegalStateException:
    // LifecycleOwner com.kxf.androidtestdemo.activity.RegisterForActivityResultActivity@7f68713 is attempting to register while current state is RESUMED.
    // LifecycleOwners must call register before they are STARTED.
    ActivityResultLauncher<Intent> resultLauncher = null;

    private HandlerThread handlerThread;
    private Handler handleMessage;
    private Messenger messenger;

    private Messenger mServiceMessenger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_for_result);
        logTxtView = findViewById(R.id.logTxtView);

        handlerThread = new HandlerThread(MSG_KEY);
        handlerThread.start();
        handleMessage = new Handler(handlerThread.getLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Bundle data = msg.getData();
                logTxtView.showTxt("RegisterForActivityResultActivity handleMessage  MSG_TO_CLIENT=" + Util.getBundleToString(data));
                switch (msg.what){
                    case MSG_CONN_SUCCESS:
                        if (data!=null){
                            IBinder binderMsg = data.getBinder(MSG_KEY);
                            try {
                                binderMsg.linkToDeath(new IBinder.DeathRecipient() {
                                    @Override
                                    public void binderDied() {
                                        logTxtView.showTxt("linkToDeath binderDied====");
                                    }
                                }, 0);
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                            mServiceMessenger = new Messenger(binderMsg);
                        }
//                    mServiceMessenger = new WeakReference<>(msg.replyTo);
                        break;
                    case MSG_TO_CLIENT:
//                    ActivityResultCallbackBean result = (ActivityResultCallbackBean) msg.obj;
                        break;
                    case MSG_DIS_CONN:
                        mServiceMessenger = null;
//                    ActivityResultCallbackBean result = (ActivityResultCallbackBean) msg.obj;
                        break;
                }
            }
        };
        messenger = new Messenger(handleMessage);
        resultLauncher = registerForActivityResult(activityResultContract, callback);
        logTxtView.showTxt("onCreate======##>>>>>>" + android.os.Process.myPid() + "   getTaskId()=" + getTaskId());
    }

    public void onClickStart(View view) {
        //registerForActivityResult在这个地方会报错
//        resultLauncher = registerForActivityResult(activityResultContract, callback);
        Intent intent = new Intent(this, RemoteServiceActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        resultLauncher.launch(intent);

    }

    public void onClickStartFragment(View view) {
        activityResultCallbackFragment = (ActivityResultCallbackFragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
        if (activityResultCallbackFragment == null){
            activityResultCallbackFragment = new ActivityResultCallbackFragment();
            getSupportFragmentManager().beginTransaction().add(activityResultCallbackFragment, TAG_FRAGMENT).commitNow();
        }
        activityResultCallbackFragment.mStartActivityForResult(RemoteServiceActivity.class);
    }

    public void onClickStartRemote(View view) {
//        resultLauncher.launch(new Intent(this, RemoteServiceActivity.class));
        remoteActivityCallback = new WeakReference<>(new IRemoteActivityCallback() {
            @Override
            public void callback(ActivityResultCallbackBean bean) {
                logTxtView.showTxt("remoteActivityCallback  bean=" + bean);
            }
        });
        Intent intent = new Intent(this, RemoteServiceActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivityForResult(intent, 100);
        startActivity(intent);
    }

    public void onClickStartRemoteFragment(View view) {
        activityResultCallbackFragment = (ActivityResultCallbackFragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
        if (activityResultCallbackFragment == null){
            activityResultCallbackFragment = new ActivityResultCallbackFragment();
            getSupportFragmentManager().beginTransaction().add(activityResultCallbackFragment, TAG_FRAGMENT).commitNow();
        }
        activityResultCallbackFragment.mResultLauncherActivity(RemoteServiceActivity.class, Intent.FLAG_ACTIVITY_NEW_TASK);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        logTxtView.showTxt("RegisterForActivityResultActivity onActivityResult " + requestCode+ " " + resultCode+ " ==>>>" + Util.getIntentExtrasToString(data));
    }

    public void onClickStartRemoteWithBinder(View view) {
        Intent intent = new Intent(this, RemoteServiceActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBinder(MSG_KEY, messenger.getBinder());
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void onClickSendMsgToService(View view) {
        handleMessage.post(new Runnable() {
            @Override
            public void run() {
                if (mServiceMessenger != null){
                    Message message = Message.obtain();
                    message.what = MSG_FROM_CLIENT;
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", 666);
                    bundle.putString("resultStr", "send msg to service " + SystemClock.elapsedRealtime());
                    message.setData(bundle);
                    try {
                        mServiceMessenger.send(message);
                        logTxtView.showTxt("mServiceMessenger  send=");
                    } catch (RemoteException e) {
                        logTxtView.showTxt("mServiceMessenger  RemoteException=");
                        e.printStackTrace();
                    }
                }else {
                    logTxtView.showTxt("mServiceMessenger  null=" + mServiceMessenger);
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handlerThread!=null){
            handlerThread.quitSafely();
        }
        messenger = null;
    }
}